package com.hw.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * NIO 的客户端程序
 * @program: NIO_Netty
 * @description:
 * @author: hewei
 * @date: 2023-03-31 11:38
 **/
public class ChannelClient {
    public static void main(String[] args) throws IOException {
        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
        Charset charset = Charset.forName("UTF-8");
        SocketChannel channel = SocketChannel.open();
        /*设置 channel 的模式 channel.configureBlocking(false);*/
        channel.connect(new InetSocketAddress("localhost",9696));

        while (channel.read(buffer) != 0){
            Long timestamp=System.currentTimeMillis();
            /*读写模式转换*/
            buffer.flip();
            System.out.println("Client received："+"["+channel.getRemoteAddress()+"]"+ charset.decode(buffer));
            buffer.flip();
            buffer.put(new String("你好，这是客户端:"+timestamp).getBytes(StandardCharsets.UTF_8));
            buffer.flip();
            channel.write(buffer);
            System.out.println("Client send：你好，这是客户端!");
            buffer.clear();
        }

    }
}
